package com.hilda.twitter.parser;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import twitter4j.EntitySupport;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.URLEntity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

/**
 * TODO: Use -> twitpic.com/show/large/[id] to download a twitpic images
 * 
 * @author olidroide
 * 
 */
public class HildaParser {
	// private static String[] URL = {
	// "http://www.google.com/",
	// "http://www.theverge.com/2011/10/18/blackberry-bbx-announced-stub/",
	// "http://hc.apache.org/httpcomponents-client-ga/",
	// "http://www.enyojs.com", "http://code.google.com/p/hilda-twitter/",
	// "http://www.elandroidelibre.com/", "http://t.co/aUYwZiSl",
	// "http://goo.gl/AaJP9", "http://twitpic.com/8jr65t",
	// "http://twitpic.com/show/large/8jr65t",
	// "http://uax.es/moviles/web/", "http://fb.me/VAp0dY24" };

	private NotifyHandler mNotifyHandler;
	private ArrayList<String> mUrlToParse;
	private HildaHtmlCleaner mHildaHtmlCleaner;
	// private int mCountUrlToParse = 0;
	// private TextView mTvDownloadText;

	public static final int DOWNLOAD_OK = 0;
	public static final int DOWNLOAD_KO = -1;

	class NotifyHandler extends Handler {

		private ArrayList<String> mUrlToParse;
		private int mCountUrlToParse = 0;

		public NotifyHandler() {

		}

		public void setUrlToParse(ArrayList<String> urlsToParse) {
			mUrlToParse = urlsToParse;
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWNLOAD_OK:
				mCountUrlToParse++;
				String filePath = (String) msg.obj;

				break;
			case DOWNLOAD_KO:
				mCountUrlToParse++;
				break;

			}

			if (mUrlToParse.size() > mCountUrlToParse) {
				mHildaHtmlCleaner.parse(mUrlToParse.get(mCountUrlToParse));
			}

			super.handleMessage(msg);
		}

	}

	public HildaParser(Context c, ResponseList<Status> timeline) {
		mNotifyHandler = new NotifyHandler();
		mUrlToParse = new ArrayList<String>();

		mHildaHtmlCleaner = new HildaHtmlCleaner(c, mNotifyHandler);
		// hildaHtmlCleaner.parse(URL[5]);

		for (Status status : timeline) {
			URLEntity urlEntities[] = status.getURLEntities();
			if (urlEntities != null && urlEntities.length > 0) {
				// hildaHtmlCleaner.parse(urlEntities[0].getExpandedURL().toExternalForm());
				for (URLEntity urlEntity : urlEntities) {
					URL url = urlEntity.getExpandedURL();
					if (url != null)
						mUrlToParse.add(url.toExternalForm());
					// mHildaHtmlCleaner.parse(urlEntity.getExpandedURL().toExternalForm());

				}
			}
		}

		if (!mUrlToParse.isEmpty()) {
			mNotifyHandler.setUrlToParse(mUrlToParse);
			mHildaHtmlCleaner.parse(mUrlToParse.get(0));
		}

	}

}